import { Component, OnInit } from '@angular/core'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { config } from '../../shared/smartadmin.config'
declare var $: any
declare var Viewer: any
@Component({
  selector: 'sa-project-event-record',
  templateUrl: './project-event-record.component.html',
  styleUrls: ['./project-event-record.component.css']
})
export class ProjectEventRecordComponent implements OnInit {
  tableData: any = [] //table数据
  totalCount: number = 0 //分页总条数
  curPage: number = 1 //分页当前页
  pageSize: number = 10 //内置的分页每页条数
  formType: string = 'add' // 新增
  initDateRange: any = {
    startTime: '',
    endTime: ''
  } // 时间组件需要渲染的值
  tableParam: any = {
    companyId: '',
    companyName: '',
    type: '',
    sort: '',
    status: '',
    startTime: '',
    endTime: '',
    searchKey: '' //搜索keyword
  }
  constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
    activatedRoute.queryParams.subscribe(queryParams => {
      this.curPage = queryParams.nowPage || 1
    })
  }
  validatorOptions = {
    excluded: [':disabled'],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      companyName: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择项目名称'
          }
        }
      },
      eventDesc: {
        validators: {
          notEmpty: {
            message: '请输入事件描述'
          }
        }
      },
      type: {
        validators: {
          notEmpty: {
            message: '请选择投诉类型'
          }
        }
      },
      sort: {
        validators: {
          notEmpty: {
            message: '请选择投诉分类'
          }
        }
      },
      status: {
        validators: {
          notEmpty: {
            message: '请选择是否解决'
          }
        }
      },
      eventTime: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择事件时间'
          }
        }
      }
    }
  }
  ngOnInit() {
    this.initDate()
    this.load()
    $('#projectEventModal').modal('hide')
  }
  // 接收子组件传递过来的数据
  getSelectTableTime(time) {
    this.tableParam.startTime = time.startTime
    this.tableParam.endTime = time.endTime
  }
  // 公司选中回调
  companySelected(data) {
    this.tableParam.companyId = data.companyId
    this.tableParam.companyName = data.companyName
  }
  //表格搜索
  table_search() {
    this.curPage = 1
    this.tableParam.searchKey = common.stringTrim(this.tableParam.searchKey)
    this.load()
  }
  //刷新
  refresh() {
    this.load()
  }
  //初始化加载list数据
  load() {
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        companyId: this.tableParam.companyId,
        type: this.tableParam.type,
        sort: this.tableParam.sort,
        status: this.tableParam.status,
        startTime: this.tableParam.startTime,
        endTime: this.tableParam.endTime,
        searchKey: this.tableParam.searchKey
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService.http('projectEvent/projectEventForPage.html', reqdata).subscribe(data => {
      if (data.exhibitDatas.length) {
        for (let i = 0; i < data.exhibitDatas.length; i++) {
          data.exhibitDatas[i].eventTime = data.exhibitDatas[i].eventTime.substr(0, 10)
        }
      }
      this.tableData = data.exhibitDatas
      this.totalCount = data.recordCount
    })
  }
  //分页回调
  paginate(e) {
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.load()
  }
  /**
   *   项目事件新增编辑模块===========================================================================================
   */
  eventForm: any = {
    id: '',
    companyName: '',
    companyId: '',
    eventDesc: '',
    type: '',
    sort: '',
    status: '',
    reason: '',
    imagePath: '',
    eventTime: '',
    principal: '',
    solveCourse: '',
    resolutionTime: ''
  }
  // 初始化时间插件
  initDate() {
    let that = this
    return new Promise(function (resolve, error) {
      System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
        System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
          $('#eventTime').datetimepicker({
            //时间插件
            format: 'yyyy-mm-dd',
            language: 'zh-CN',
            autoclose: true,
            minView: 2
          })

          $('#resolutionTime').datetimepicker({
            //时间插件
            format: 'yyyy-mm-dd',
            language: 'zh-CN',
            autoclose: true,
            minView: 2
          })
          resolve()
        })
      })
    })
  }
  // 添加项目事件界面打开
  showAddUserModal() {
    this.formType = 'add'
    let that = this
    this.imageInfo = {
      imageList: [],
      describe: '项目事件相关图片'
    }
    let nowTime = new Date().toLocaleDateString().replace(/\//g, '-')
    this.eventForm = {
      id: '',
      companyName: '',
      companyId: '',
      eventDesc: '',
      type: '',
      sort: '',
      status: '',
      reason: '',
      imagePath: '',
      eventTime: nowTime,
      principal: '',
      solveCourse: '',
      resolutionTime: ''
    }
    // $('#eventTime').val('');
    $('#resolutionTime').val('')
    // modal.show();
    $('#projectEventModal').modal('show')
  }
  // 编辑项目事件
  editRow(row) {
    this.formType = 'update'
    for (let key in this.eventForm) {
      this.eventForm[key] = row[key]
    }
    this.imageInfo = {
      imageList: [],
      describe: '项目事件相关图片'
    }
    //显示图片
    this.imageInfo.imageList = row.imagePath ? row.imagePath.split(',') : []
    // modal.show();
    $('#projectEventModal').modal('show')
  }
  //新增或者编辑公司选中回调
  companySelectedForm(data) {
    this.eventForm.companyId = data.companyId || ''
    this.eventForm.companyName = data.companyName
  }
  // 添加项目事件关闭
  closeProjectEventModal() {
    $('#projectEventForm').data('bootstrapValidator').resetForm()
    // modal.hide();
    $('#projectEventModal').modal('hide')
  }
  // 提交
  projectEventSubmit() {
    this.eventForm.eventTime = $('#eventTime').val()
    this.eventForm.resolutionTime = $('#resolutionTime').val()
    $('#projectEventForm').bootstrapValidator('validate') //开启验证
    let isValid = $('#projectEventForm').data('bootstrapValidator').isValid() //验证是否通过
    if (isValid) {
      this.eventForm.imagePath = this.imageInfo.imageList.join(',')
      let Url: string = 'projectEvent/addProjectEvent.html'
      if (this.formType == 'update') {
        Url = 'projectEvent/editProjectEvent'
      }
      this.jsonApiService.http_obj(Url, this.eventForm).subscribe(data => {
        if (data.success) {
          this.closeProjectEventModal()
          this.load()
        }
        this.jsonApiService.message(data.message)
      })
    }
  }
  // 删除
  delRow(row) {
    this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(() => {
      let reqdata = 'id=' + row.id
      this.jsonApiService.http('projectEvent/deleteById.html', reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        this.load()
      })
    })
  }
  /**
   * 图片的方法
   */
  imgList: any = []
  imgLocalList: any = []
  isViewer: boolean = false //默认隐藏
  isViewer1: boolean = false //默认隐藏
  //显示图片组件
  viewer1: any = ''
  imageInfo: any = {
    imageList: [],
    describe: '项目事件相关图片'
  }

  //显示图片组件
  viewer: any = ''
  fileList: File = null

  bigImgClick() {
    // modal.show();
    if (this.isViewer && $('.viewer-container').length > 0) {
      System.import('assets/js/viewer/viewer.js').then(() => {
        System.import('assets/js/viewer/bootstrap.bundle.min.js').then(() => {
          System.import('assets/js/viewer/viewer.css').then(() => {
            this.showImg()
          })
        })
      })
    } else {
      this.showImg()
    }
  }
  showImg() {
    var imgList = $('.imgFileList')[0]
    this.viewer = new Viewer(imgList, {
      url: 'src',
      title: function (image) {
        return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')'
      }
    })
    this.isViewer = true
  }
  //上传多张
  multifileChange(files: FileList) {
    if (this.isViewer && $('.viewer-container').length > 0) {
      this.viewer.destroy()
    }
    let multfileList = files
    var reqdata = new FormData()
    reqdata.append('describe', this.imageInfo.describe)
    reqdata.append('businessType', '3')
    reqdata.append('type', '2') //type 1获取相对路径  2获取绝对路径
    for (var i = 0; i < multfileList.length; i++) {
      this.fileList = multfileList[i]
      const isJPG =
        this.fileList.type === 'image/jpeg' || this.fileList.type === 'image/jpg' || this.fileList.type === 'image/png'
      if (!isJPG) {
        this.jsonApiService.message('上传图片只能是 png, jpg, jpeg 格式!')
        return
      }
      reqdata.append('files', multfileList[i])
    }
    this.jsonApiService.form_http('fileUpload/upload.html', reqdata).subscribe(data => {
      if (data.success) {
        for (var i = 0; i < data.data.length; i++) {
          this.imageInfo.imageList.push(data.data[i])
        }
      }
    })
    for (let k = 0; k < $('.up').length; k++) {
      $('.up')[k].value = null
    }
  }

  //删除图片
  deleteImg(index, i) {
    if (index == 1) {
      this.imageInfo.imageList.splice(i, 1)
    }
    if (this.isViewer && $('.viewer-container').length > 0) {
      this.viewer.destroy()
    }
  }
  // 关闭图片查看
  closeImgModal1(modal) {
    modal.hide()
    this.imgList = []
    this.imgLocalList = []
  }

  // 点击Table中的查看图片
  showImg1(row, modal) {
    this.imgList = []
    this.imgLocalList = []
    this.imgList = row.imagePath.split(',')
    let localImg
    for (var i = 0; i < this.imgList.length; i++) {
      localImg = this.imgList[i]
      this.imgLocalList.push(localImg)
    }
    modal.show()
    if (this.isViewer1 && $('.viewer-container').length > 0) {
      this.viewer1.destroy()
    }
  }
  bigimg() {
    if (this.isViewer1 && $('.viewer-container').length > 0) {
      System.import('assets/js/viewer/viewer.js').then(() => {
        System.import('assets/js/viewer/bootstrap.bundle.min.js').then(() => {
          System.import('assets/js/viewer/viewer.css').then(() => {
            this.showBigImg()
          })
        })
      })
    } else {
      this.showBigImg()
    }
  }
  showBigImg() {
    var imgList = $('.imagesInfo1')[0]
    this.viewer1 = new Viewer(imgList, {
      url: 'src',
      title: function (image) {
        return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')'
      }
    })
    this.isViewer1 = true
  }
}
